package cn.xw.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author AnHui OuYang
 * @version 1.0
 * created at 2023-04-20 16:56
 * RabbitMQ配置
 */
@Configuration
public class RabbitMQConfig {

    //普通直接交换机
    public static final String ORDINARY_DIRECT_EXCHANGE = "ordinaryDirectExchange";
    //普通队列
    public static final String ORDINARY_QUEUE = "ordinaryQueue";
    //路由key
    public static final String ROUTE_KEY = "routeKey";

    /***
     * 创建直接交换机
     * @return Exchange
     */
    @Bean("ordinaryDirectExchange")
    public Exchange ordinaryDirectExchange() {
        return ExchangeBuilder.directExchange(ORDINARY_DIRECT_EXCHANGE).durable(true).build();
    }

    /***
     * 创建普通队列(并且添加优先级的配置)
     * @return Queue
     */
    @Bean("ordinaryQueue")
    public Queue ordinaryQueue() {
        //其它参数
        Map<String, Object> arguments = new HashMap<>();
        //设置优先队列的值范围，官方允许0~255，设置10代表优先级范围为10，设置过大，后面排序耗费资源和CPU
        //代表后期生产者在投递消息时需要设置消息的0~10的优先级，越大越先执行
        //arguments.put("x-max-priority", 10);
        //设置惰性队列
        arguments.put("x-queue-mode", "lazy");
        //构建队列
        return QueueBuilder.durable(ORDINARY_QUEUE).withArguments(arguments).build();
    }

    /***
     * 绑定关系
     * @param exchange 交换机
     * @param queue 队列
     * @return Binding
     */
    @Bean("ordinaryQueueBindOrdinaryDirectExchange")
    public Binding ordinaryQueueBindExchange(@Qualifier("ordinaryDirectExchange") Exchange exchange,
                                             @Qualifier("ordinaryQueue") Queue queue) {
        return BindingBuilder.bind(queue).to(exchange).with(ROUTE_KEY).noargs();
    }
}
